<?php
  include("include/config.inc.php");
  $itemIdVar = $_POST['itemIdVar'];
  $waiterVar  = $_POST['waiterVar'];
  $tableVar  = $_POST['tableVar'];
  $tablePartVar  =$_POST['tablePartVar'];
  $startTime = date('H:i');
  
  $selectOrder = "SELECT orderId 
                    FROM ordermaster 
                   WHERE waiterId = '$waiterVar'
                     AND tableId = '$tableVar'
                     AND tablePart = '$tablePartVar'
                     AND orderstatus = 'L' ";
  $orderRes = mysql_query($selectOrder);
  $orderRow = mysql_fetch_array($orderRes);
  $orderNum = mysql_num_rows($orderRes);
  
  if($orderNum == 0)
  {
    $insertOrder = "INSERT INTO  ordermaster (waiterId, tableId, tablePart, startTime, orderstatus)
                           VALUES('$waiterVar','$tableVar','$tablePartVar','$startTime','L')";
    $insertRes = mysql_query($insertOrder);
    
    $selectOederMaster = " SELECT orderId 
                             FROM ordermaster 
                            WHERE waiterId = '$waiterVar'
                              AND tableId = '$tableVar'
                              AND tablePart = '$tablePartVar'
                              AND orderstatus = 'L' ";
    $selectOederMasterRes = mysql_query($selectOederMaster);
    $selectOederMasterRow = mysql_fetch_array($selectOederMasterRes);
    $orderId = $selectOederMasterRow['orderId'];
    
    $insertOrderedItems = "INSERT INTO ordereditems (orderId,itemId,quantity,orderTime)
                                VALUES ('$orderId','$itemIdVar','1','$startTime')";
    $insertOrderedItemsRes = mysql_query($insertOrderedItems);
  }
  else 
  {
    $orderId = $orderRow['orderId'];
    $selectItem = "SELECT itemId
                     FROM ordereditems 
                    WHERE itemId =".$itemIdVar." 
                      AND orderId = ".$orderId;
    $selectItemRes = mysql_query($selectItem);
    $selectItemRow = mysql_fetch_array($selectItemRes);
    if(!$selectItemRow['itemId'])
    {
      $insertOrderedItems = "INSERT INTO ordereditems (orderId,itemId,quantity,orderTime)
                                 VALUES ('$orderId','$itemIdVar','1','$startTime')";
      $insertOrderedItemsRes = mysql_query($insertOrderedItems);
    }
  }
    
?>
<table align="center" cellpadding="6">
 <!-- <tr>
    <td align="right" class="links"> 
      <a href="closeTables.php">Close Table</a>|<a href="checklogin.php">LogIn</a>
    </td>
  </tr> -->
  <tr>
    <td>
      <iframe src="currentTables.php?waiter=<?php echo $waiterVar; ?>&table=<?php echo $tableVar; ?>&orderId=<?php echo $orderId; ?>" width="500" height="350"></iframe>
    </td>
  </tr>
  <tr>
    <td>
      <iframe id="selectedTableIframe" src="selectedTable.php?waiterId=<?php echo $waiterVar; ?>&tableId=<?php echo $tableVar; ?>&tablePart=<?php echo $tablePartVar; ?>" width="500" height ="490"></iframe>
    </td>
  </tr>
</table>